package com.lmind.support.web;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lmind.bean.BeanWalker;
import com.lmind.bean.IObjectVisitor;
import com.lmind.bean.IWalkerContext;

/**
 * 执行html转义工作
 * 
 * @author 刘勉
 * 
 */
public class HtmlTagEscape {
	
	private Logger logger = LoggerFactory.getLogger(HtmlTagEscape.class);

	private BeanWalker walker = new BeanWalker();

	public HtmlTagEscape() {
		
		walker.setVisitor(new IObjectVisitor() {
			@Override
			public void visitProperty(IWalkerContext context) {
				escapeHtmlTag(context);
			}

			@Override
			public void visitMap(IWalkerContext context) {
				escapeHtmlTag(context);
			}

			@Override
			public void visitList(IWalkerContext context) {
				escapeHtmlTag(context);
			}

			@Override
			public void visitArray(IWalkerContext context) {
				escapeHtmlTag(context);
			}
		});
	}

	public List<String> getIncludePackages() {
		return walker.getIncludePackages();
	}

	public void setIncludePackages(List<String> includePackages) {
		walker.setIncludePackages(includePackages);
	}

	/**
	 * 扫描bean的所有字符串属性,并执行html转义
	 * 
	 * @param bean
	 *            bean
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public void escapeBean(Object bean) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		walker.walk(bean);
	}

	/**
	 * 转义字符穿
	 * 
	 * @param origin
	 *            原始字符串
	 * @return 转移后的字符串
	 */
	public static String escape(String origin) {

		StringBuilder sb = new StringBuilder();
		for (char c : origin.toCharArray()) {

			if (c == '<') {
				sb.append("&lt;");
			} else if (c == '>') {
				sb.append("&gt;");
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	private void escapeHtmlTag(IWalkerContext context) {
		
		if (context.getValue() instanceof String) {
			String value = (String) context.getValue();
			String v = escape(value);
			if (!v.equals(value)) {
				context.setValue(v);
				logger.debug("完成html转义，原始字符串：  " + value);
			}
		}
	}

}
